package com.example.cs4.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.cs4.controller"))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .securitySchemes(Collections.singletonList(apiKey())) // 添加安全方案
                .securityContexts(Collections.singletonList(securityContext())); // 添加安全上下文
    }

    private ApiKey apiKey() {
        return new ApiKey("JWT", "Authorization", "header"); // 定义一个名为 "JWT" 的安全方案
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth()) // 引用安全方案
                .forPaths(PathSelectors.any()) // 应用于所有路径
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        return Collections.singletonList(new SecurityReference("JWT", new AuthorizationScope[]{authorizationScope}));
    }
    private ApiInfo apiInfo() {
        return new ApiInfo(
                "海带 API 文档", // 标题
                "提供图书借阅相关的接口文档", // 描述
                "v1.0", // 版本号
                "海带 of service", // 服务条款
                new Contact("海带", "https://example.com", "海带@example.com"), // 联系人信息
                "海带 of API", // 许可证
                "API 海带 URL", // 许可证 URL
                Collections.emptyList() // 扩展信息
        );
    }
}